package com.easymall.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 基于C3P0的JDBC数据库连接池工具类
 */
public class JDBCUtils {

    private static ComboPooledDataSource cpds;

    static {
        cpds = new ComboPooledDataSource("mariadb-config");
        // System.out.println(cpds.getDriverClass());
        cpds.setUser("root");
        cpds.setPassword("root");
        try {
            cpds.setDriverClass("org.mariadb.jdbc.Driver");
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        cpds.setJdbcUrl("jdbc:mariadb://localhost:3306/easymall");

    }

    private JDBCUtils(){}

    /**
     * 从数据库连接池中获取一个连接并返回
     * @return 数据库连接对象Connection
     * @throws SQLException 数据库连接获取失败
     */
    public static Connection getConnection() throws SQLException {
        return cpds.getConnection();
    }

    /**
     * 将连接归返连接池并释放相关的资源
     * @param resultSet 要释放的结果集对象
     * @param statement 要释放的SQL执行器对象
     * @param connection 要归还的连接对象
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                resultSet = null;
            }
        }
        if ( null!=statement){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                statement = null;
            }
        }
        if (null!=connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                connection = null;
            }
        }
    }

}
